<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="queryForm" :inline="true" :model="listQuery" label-position="left" label-width="120px" style="margin-left:30px;">
                <el-form-item :label="$t('table.package')" style="width:30%">
                    <el-select v-model="listQuery.package" :placeholder="$t('table.package')" clearable style="width: 150px" class="filter-item">
                        <el-option v-for="item in packageOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('table.delivery_date')" style="width:50%">
                    <el-date-picker
                        v-model="listQuery.deliveryDate"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.delivery_from')"
                        :end-placeholder="$t('placeholder.delivery_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <report-check v-for="(opt, idx) in locationOptions" :check-items="checkIds" :opt="opt" :key="idx" :idx="idx" @change-check="changeCheck"></report-check>
            </el-form>
            <el-row class="button-box" >
                <el-col :span="12" style="text-align: left"> <el-checkbox v-model="checkAll" label="99999" @change="handleCheckAllChange">Select All</el-checkbox></el-col>
                <el-col :span="12"> 
                    <el-button v-waves class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
                    <el-button v-waves class="filter-item" type="success" icon="el-icon-download" @click="onDownLoad1">Full Excel</el-button>
                    <el-button v-waves class="filter-item" type="success" icon="el-icon-download" @click="onDownLoad2">Delivery Note</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="report-list-box">
            <el-tabs v-model="editableTabsValue" type="card" @tab-click="handleClick">
                <el-tab-pane
                    label="Juice"
                    name="juice"
                >
                <table style="width: 100%" class="report-table">
                    <thead>
                        <tr>
                            <th rowspan="2" width="20%">Item</th>
                            <th colspan="5" width="26.6%" v-for="(item, i) in reports.days" :key="i" v-text="item"></th>
                        </tr>
                        <tr>
                            <th width="4.806%">{{$t('table.public')}}</th>
                            <th width="6.75%">{{$t('table.workshop')}}</th>
                            <th width="4.806%">{{$t('table.event')}}</th>
                            <th width="4.806%">{{$t('table.online')}}</th>
                            <th width="5.46%">{{$t('table.total')}}</th>
                            
                            <th width="4.806%" v-if="reports.days.length > 1">{{$t('table.public')}}</th>
                            <th width="6.75%" v-if="reports.days.length > 1">{{$t('table.workshop')}}</th>
                            <th width="4.806%" v-if="reports.days.length > 1">{{$t('table.event')}}</th>
                            <th width="4.806%" v-if="reports.days.length > 1">{{$t('table.online')}}</th>
                            <th width="5.46%" v-if="reports.days.length > 1">{{$t('table.total')}}</th>
                            
                            <th width="4.806%" v-if="reports.days.length > 2">{{$t('table.public')}}</th>
                            <th width="6.75%" v-if="reports.days.length > 2">{{$t('table.workshop')}}</th>
                            <th width="4.806%" v-if="reports.days.length > 2">{{$t('table.event')}}</th>
                            <th width="4.806%" v-if="reports.days.length > 2">{{$t('table.online')}}</th>
                            <th width="5.46%" v-if="reports.days.length > 2">{{$t('table.total')}}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, i) in juiceObject" :key="i" style="line-height:30px;">
                            <td>
                                <div>{{item.name}}</div>
                            </td> 
                            <td  v-for="(con, j) in item.count" :key="j" colspan="5">
                                <div v-for="(cell, t) in con" :key="t" :style="{display:'inline-block', width: t==1 ? '25%' :  t==4 ? '21%' : '18%'}">{{cell}}</div>
                            </td>
                        </tr>
                    </tbody>
                    <tbody v-if="!juiceObject || juiceObject.length <=0" class="el-table__body-wrapper is-scrolling-none">
                        <tr><td colspan="6"><div class="el-table__empty-block"><span class="el-table__empty-text">No Data</span></div></td></tr>
                    </tbody>
                </table>
                   
                </el-tab-pane>
                <el-tab-pane
                    label="Delivery"
                    name="delivery"
                    class="report-count-box"
                >
                    <el-row>
                        <el-col :span="8">Package</el-col>
                        <el-col :span="8">Business</el-col>
                        <el-col :span="8">Location</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <div v-for="(item, i) in reports.stat.group" :key="i">
                                <span class="label">{{item.name}}：</span>
                                <span>{{item.count}}</span>
                            </div>
                            <div>
                                <span class="label">Total：</span>
                                <span>{{totalData.packageTotal}}</span>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div v-for="(item, i) in reports.stat.business" :key="i">
                                <span class="label">{{item.name}}：</span>
                                <span>{{item.count}}</span>
                            </div>
                            <div>
                                <span class="label">Total：</span>
                                <span>{{totalData.businessTotal}}</span>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div v-for="(item, i) in reports.stat.location" :key="i">
                                <span class="label">{{item.name}}：</span>
                                <span>{{item.count}}</span>
                            </div>
                            <div>
                                <span class="label">Total：</span>
                                <span>{{totalData.locationTotal}}</span>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 20px; text-align: right;">
                        <el-col><el-button v-waves class="filter-item" type="success" icon="el-icon-download" @click="onDownLoadDelivery">Excel</el-button></el-col>
                    </el-row>
                    <el-table
                        v-loading="listLoading"
                        :key="tableKey"
                        :data="reports.orderGroups"
                        border
                        fit
                        highlight-current-row
                        style="width: 100%;">
                        <el-table-column :label="$t('order_form.order_from')" align="center" width="65">
                            <template slot-scope="scope">
                                <span>{{ scope.row.order_from === 3 ? 'Online' : scope.row.order_from === 2 ? 'Even' : scope.row.order_from === 1 ? 'Workshop' : 'Public'}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.ref_no')" align="center" width="100">
                            <template slot-scope="scope">
                                <span>{{ scope.row.order_sn }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.name')" align="center" width="100">
                            <template slot-scope="scope">
                                <div>{{ scope.row.name }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.contact')" align="center" width="100">
                            <template slot-scope="scope">
                                <span>{{ scope.row.mobile }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.package')" align="center" width="160">
                            <template slot-scope="scope">
                                <span>{{ scope.row.group_name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.location')" align="left">
                            <template slot-scope="scope">
                                <span>{{ scope.row.location_type }} - {{ scope.row.location_type === 'Home Delivery' ? scope.row.location_name + ' ' + scope.row.area_region_name + ' ' + scope.row.address : scope.row.location_name}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.juice_list')" align="left">
                            <template slot-scope="scope">
                                <div v-for="(item, index) in scope.row.product" :key="index">{{item.qty}} - {{item.product_name}}{{item.product_scode}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.customized')" align="center" width="120">
                            <template slot-scope="scope">
                                <span>{{ scope.row.is_custom ? 'YES' : 'NO' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.delivery_date')" align="center" width="100">
                            <template slot-scope="scope">
                                <span>{{ scope.row.scheduled_at }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('table.order_date')" align="center" width="90">
                            <template slot-scope="scope">
                                <span>{{ scope.row.order_date }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div>Total: {{reports.orderGroups ? reports.orderGroups.length : 0}}</div>
                </el-tab-pane>
            </el-tabs>
        </div>     
    </div>
</template>
<script>
import { fetchAll } from '@/api/location'
import { fetchReport } from '@/api/report'
import waves from '@/directive/waves' // Waves directive
import i18n from '@/lang/index'
import { urlEncode, setLocationType, parseTime, formatData } from '@/utils'
import { fetchAll as fetchGroupList } from '@/api/group'
import ReportCheck from '@/components/ReportCheck'
export default {
    name: 'Report',
    directives: { waves },
    components: {
        ReportCheck
    },
    data () {
        return {
            tableKey: 0,
            listLoading: false,
            packageOptions: [
                {
                    name: i18n.t('order_element.package.all'),
                    value: 0
                }
            ],
            listQuery: {
                page: 1,
                limit: 20,
                package:'',
                location: [],
                deliveryDate: '',
                lang: i18n.locale,
            },
            checkAll: false,
            list: [],
            editableTabsValue: 'juice',
            reports:{
                days: [],
                orders: [{
                    "product":[]
                }],
                "stat":{
                    "juice":[],
                    "group":[],
                    "business":[],
                    "location":[]
                }
            },
            juiceObject: [],
            locationOptions: [],
            locationAllOptions: [],
            checkIds: [],
            allIds: [],
            totalData: {
                packageTotal: 0,
                businessTotal: 0,
                locationTotal: 0
            }
        }
    },
    watch: {
    	checkIds: function(val) {
            this.listQuery.location = val
    	}
    },
    mounted () {
        this.getLocation()
        this.getGroupList()
    },
    methods: {
        resetTemp() {
            this.reports = {
                days: [],
                orders: [{
                    "product":[]
                    }
                ],
                "stat":{
                    "juice":[],
                    "group":[],
                    "business":[],
                    "location":[]
                }
            }
            this.juiceObject = []
            this.totalData = {
                packageTotal: 0,
                businessTotal: 0,
                locationTotal: 0
            }
        },
        getLocation() {// 地址列表
            let _this = this
            let params = {
                pid: 0,
                area: this.$store.getters.area
            }
            fetchAll(params).then((res) => {
                let datas = res.data.data
                _this.locationOptions = setLocationType(datas)
                for (let i=0; i < _this.locationOptions.length; i++) {
                    _this.locationAllOptions.push([])
                    for (let j=0; j < _this.locationOptions[i].child.length; j++) {
                        _this.locationAllOptions[i].push(_this.locationOptions[i].child[j].id)
                    }
                }
                let ids = []
                _this.locationOptions.forEach(ele => {
                    ele.child.forEach(element => {
                        ids.push(element.id)
                    })
                })
                _this.allIds = ids
                _this.$nextTick(() => {
                    _this.changeCheck(_this.allIds) // 默认选中
                })
                _this.getReport()
            })
        },
        getGroupList() {
            let params = {
                lang: i18n.locale,
                /* area: 96,
                name: '' */
            }
            fetchGroupList(params).then((res) => {
                if (res.data.data.length > 0) {
                    this.packageOptions = res.data.data
                }
            })
        },
        getJuice(data) {
            let dts = []
            for (let item in data) {
                let ret = {}
                let perObj = {}
                for (let per in data[item]) {
                    ret = {
                        name: data[item][per].name,
                        product_id: data[item][per].product_id,
                        count: {}
                    }
                    perObj[per] = data[item][per].count
                    perObj = Object.assign({}, perObj)
                }
                ret.count = perObj
                dts.push(ret) 
            }
            return dts
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getReport()
        },
        getReport() {
            this.listLoading = true
            let _this = this
            if (this.listQuery.deliveryDate) {
                this.listQuery.delivery_date = [formatData(this.listQuery.deliveryDate[0]).substr(0, 10), formatData(this.listQuery.deliveryDate[1]).substr(0, 10)]
            } else {
                delete this.listQuery.delivery_date
            }
            let goupTotal = 0
            let businessTotal = 0
            let locationTotal = 0
            fetchReport(this.listQuery).then(res => {
                var data = res.data
                if (data.data) {
                    _this.reports = data.data
                    _this.juiceObject = _this.getJuice(_this.reports.stat.juice)
                    _this.reports.stat.group.forEach(ele => {
                        goupTotal += ele.count
                    })
                    _this.reports.stat.business.forEach(ele => {
                        businessTotal += ele.count
                    })
                    _this.reports.stat.location.forEach(ele => {
                        locationTotal += ele.count
                    })
                    _this.totalData = {
                        packageTotal: goupTotal,
                        businessTotal: businessTotal,
                        locationTotal: locationTotal,
                    }
                } else {
                    _this.resetTemp()
                }
                this.listLoading = false
            })
        },
        handleClick(tab, event) {
            console.log(tab, event)
        },
        onDownLoad1() { //跳转下载页
            let query = urlEncode(this.listQuery)
            let url = process.env.BASE_API + '/admin/order-report-export?1=1' + query
            window.open(url)
        },
        onDownLoad2() { //跳转下载页
            if (this.listQuery.delivery_date) {
                this.listQuery.delivery_date = [formatData(this.listQuery.deliveryDate[0]).substr(0, 10), formatData(this.listQuery.deliveryDate[1]).substr(0, 10)]
                let query = urlEncode(this.listQuery)
                let url = process.env.BASE_API + '/admin/order-report-delivery-note?1=1' + query
                window.open(url)
            } else {
                this.$message.error('Please select Delivery Date！');
            }
        },
        changeCheck(ids) {
            console.log(ids)
			this.checkIds = ids
            if (this.checkIds.length !== this.allIds.length) {
                this.checkAll = false
            } else {
                this.checkAll = true
            }
        },
        handleCheckAllChange(val) {
            if (val) {
			    this.checkIds = JSON.parse(JSON.stringify(this.allIds))
            } else {
                this.checkIds = []
            }
        },
        onDownLoadDelivery() { //导出
            if (this.listQuery.delivery_date) {
                this.listQuery.delivery_date = [formatData(this.listQuery.deliveryDate[0]).substr(0, 10), formatData(this.listQuery.deliveryDate[1]).substr(0, 10)]
            } else {
                delete this.listQuery.delivery_date
            }
            let query = urlEncode(this.listQuery)
            let url = process.env.BASE_API + '/admin/order-report-delivery-export?1=1' + query
            window.open(url)
        }
    }
}
</script>
<style rel="stylesheet/scss" lang="scss" >
.ckeckedLocation{
    .el-checkbox{
        display: block;
    }
}
.report-list-box{
    .el-table {
        font-size: 12px;
    }
    .report-table{
        border-collapse: collapse;
        td,th{
            border: 1px solid #eee;
            line-height: 20px;
            padding: 5px;
            text-align: center;
        }
        tr td:first-child{
            text-align: left;
        }
    }
    .report-count-box{
        line-height: 30px;
        .el-col-8{
            text-align: center; 
        }
        span{ 
            display: inline-block;
        }
        .label{
            width: 35%;
            text-align: right;
        }
    }
}
</style>
